<?php

$enable_profiling = 1;

if (isset($_GET["edit"]))
{
	session_start();
	require_once 'ajax.inc';
	
	if (isset($_SESSION["user"]))
		$user = $_SESSION["user"];
	else 
	{
		echo "not logged";
		return;
	}
	$top = "admin";
}
else
{
	$top = "common";
}

$content = "tournament";
$side = "tournament";

require_once("sys.inc");

$tournament_id = 0;

if (isset($_GET["id"]) && preg_match("/^\d+$/", $_GET["id"]))
{
	$tournament_id = $_GET["id"] + 0; 
}

if ($tournament_id == 0)
	err("Invalid tournament ID: " . $_GET["id"]);


$q = "SELECT * FROM $table_tournament
LEFT JOIN $table_country ON $table_country.country_id=$table_tournament.country_id
LEFT JOIN $table_city ON $table_city.city_id=$table_tournament.city_id
WHERE tournament_id=$tournament_id";

$result = mysql_query($q);
while ($row = mysql_fetch_object($result))
{
	$tournament = $row;
}
if (!isset($tournament))
	err("Tournament not found: " . $_GET["id"]);

$q = "SELECT * FROM $table_game WHERE tournament_id = $tournament_id";
$glist = Array();
$result = mysql_query($q);
$gcond = Array();
$pcond = Array();
while ($row = mysql_fetch_object($result))
{
	array_push($glist, $row);
	array_push($gcond, "(game_id=" . $row->game_id . " AND player_id=" . $row->black_id .")");
	$pcond["player_id=" . $row->black_id]++;
	$pcond["player_id=" . $row->white_id]++;
}

$pdict = get_pdict(join(" OR ", array_keys($pcond)));

$q = "SELECT * FROM $table_rating WHERE tournament_id = $tournament_id";
$result = mysql_query($q);
while ($row = mysql_fetch_object($result))
{
	$pdict[$row->player_id]->rating = $row->player_end_rating; 
}

$cond = join(" OR ", $gcond);
if ($cond == "")
	$cond = "0";
$q = "SELECT * FROM $table_log WHERE " . join(" OR " ,$gcond);
$result = mysql_query($q);
$glog = Array();
while ($row = mysql_fetch_object($result))
{
	array_push($glog, $row);
}

function rcmp($a, $b)
{
	if ($a->round_key == $b->round_key)
		return 0;
	return $a->round_key <	$b->round_key ? -1 : 1;
}

usort($glog, "rcmp");

require 'tpl/index.tpl';

?>